package com.example.spring.test;

public class HasSelfPrivateNum {

    private int num = 0;

    public static void main(String[] args) {

        HasSelfPrivateNum numRef = new HasSelfPrivateNum();

        ThreadTestA thread1 = new ThreadTestA(numRef);
        thread1.start();

        ThreadTestB thread2 = new ThreadTestB(numRef);
        thread2.start();
    }

    synchronized public void add(String username) {
        try {
            if (username.equals("a")) {
                num = 100;
                System.out.println("a set over!");

                Thread.sleep(2000);
            } else {
                num = 200;
                System.out.println("b set over!");
            }
            System.out.println(username + " num=" + num);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static public class ThreadTestA extends Thread {
        private HasSelfPrivateNum numRef;

        public ThreadTestA(HasSelfPrivateNum numRef) {
            this.numRef = numRef;
        }

        @Override
        public void run() {
            numRef.add("a");
        }
    }

    static public class ThreadTestB extends Thread {
        private HasSelfPrivateNum numRef;

        public ThreadTestB(HasSelfPrivateNum numRef) {
            this.numRef = numRef;
        }

        @Override
        public void run() {
            numRef.add("b");
        }
    }
}
